import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login/index.vue'
/* 引入异步路由 */
import { asyncRouter } from './asyncRouter'
/* 引入本地存储 */
import local from '../utils/local'

Vue.use(VueRouter)
/* 解决重复点击导航问题 */
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/login',
    name: 'login',
    meta: { name: '登录', title: '登录' },
    component: Login
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    name: '404',
    component: () =>
      import(/* webpackChunkName: "error" */ '../views/Error/404.vue')
  }
]

const router = new VueRouter({
  routes
})

separationRouter()
export function separationRouter() {
  const role = local.get('role')
  if (!role) return false
  /* 过滤出来的数组 */
  const fliterArr = hasPermission(asyncRouter.children, role)
  /* 合并异步路由 */
  asyncRouter.children = fliterArr
  router.addRoute(asyncRouter)

  /* 计算菜单 */
  const listMenu = filterMenu(fliterArr)
  local.set('listMenu', JSON.stringify(listMenu))
}
/* 过滤出符合权限的路由 */
function hasPermission(arr, k) {
  return arr.filter(item => {
    /* 有标识符的 */
    if (item.meta && item.meta.role) {
      /* 如果还有子菜单 */
      if (item.children) {
        item.children = hasPermission(item.children, k)
      }
      return item.meta.role.includes(k)
    } else {
      /* 没有标识符的都可以访问 */
      return true
    }
  })
}
/* 过滤菜单 */
function filterMenu(arr) {
  return arr.filter(item => {
    if (item.hidden) {
      if (item.children) {
        item.children = filterMenu(item.children)
      }
      return false
    } else {
      if (item.children) {
        item.children = filterMenu(item.children)
      }
      return true
    }
  })
}

/* 全局导航守卫 */
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  document.title = to.meta.title
  if (to.name !== 'login' && !token) next({ name: 'login' })
  else next()
})
export default router
